package com.app.biz.utils;

import cn.hutool.core.util.IdUtil;

import com.alibaba.fastjson2.JSONObject;
import com.app.biz.domain.BizAppChatMsg;
import com.app.biz.mapper.BizAppChatMsgMapper;
import com.app.biz.server.ChatMessageServer;
import com.app.common.core.domain.model.LoginUser;
import com.app.common.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class ChatMessageUtils {

    protected final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BizAppChatMsgMapper bizAppChatMsgMapper;

    @Autowired
    private ChatMessageServer chatMessageServer;

    @Transactional(rollbackFor = Exception.class)
    public void saveAndSendMessage(BizAppChatMsg chatMsg) {
        BizAppChatMsg oldMessageRecord = new BizAppChatMsg();
        oldMessageRecord.setBaseId(chatMsg.getBaseId());
        oldMessageRecord.setStatus(1L);
        bizAppChatMsgMapper.updateBizAppChatMsg(oldMessageRecord);
        chatMsg.setStatus(1L);
        chatMsg.setBaseId(IdUtil.fastUUID());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser != null ? loginUser.getUserId() : null;
        chatMsg.setSenderId(userId != null ? String.valueOf(userId) : null);
        try{
            chatMessageServer.saveAndSendMessage(JSONObject.toJSONString(chatMsg));
        }catch (Exception e){
            log.error("发送消息失败",e.getMessage());
        }

    }
}
